<template>
  <div class="cropper-upload">
    <!-- 上传按钮 -->
    <!-- :action="uploadImgUrl" -->
    <!-- :data="{ accountId: appStore.accountId, advertiserId: '1817579513196555' }" -->

    <el-upload
      v-model:file-list="fileList"
      ref="uploadRef"
      :action="uploadImgUrl"
      list-type="picture-card"
      :auto-upload="false"
      :show-file-list="true"
      :headers="headers"
      :accept="accept"
      :disabled="disabled"
      :on-change="beforeUpload"
      :limit="props.limit"
      :on-exceed="handleExceed"
    >
      <el-icon><Plus /></el-icon>
      <template #tip>
        <div class="el-upload__tip" v-if="tip">
          {{ tip }}
        </div>
      </template>
    </el-upload>
    <!-- 裁剪对话框 -->
    <el-dialog v-model="cropperVisible" :title="dialogTitle" width="800px" append-to-body @closed="resetCropper">
      <div class="flex imgbox">
        <div class="cropper-wrapper w-[340px] h-[300px] overflow-hidden">
          <vue-cropper
            ref="cropperRef"
            :img="options.img"
            :info="true"
            :auto-crop="options.autoCrop"
            :auto-crop-width="autoCropWidth"
            :auto-crop-height="autoCropHeight"
            :fixed-number="props.fixedNumber"
            :fixed-box="props.fixedBox"
            :fixed="props.fixed"
            :center-box="props.centerBox"
            :output-type="options.outputType"
            @real-time="realTime"
          />
        </div>
        <div class="w-[340px] h-[300px] ml-auto relative overflow-hidden preview">
          <div class="imgafter" :style="`width:${autoCropWidth}px;height:${autoCropHeight}px`">
            <img :src="options.previews.url" :style="options.previews.img" />
          </div>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="cancel">取消</el-button>
          <el-button type="primary" @click="handleCrop">确认裁剪</el-button>
          <!-- <el-button v-if="showRotate" @click="rotateImage">旋转</el-button>
          <el-button v-if="showFlip" @click="flipImage">翻转</el-button> -->
          <el-button v-if="showReset" @click="resetCropper">重置</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
// import { ref, computed } from 'vue';
// import { ElMessage, ElLoading } from 'element-plus';
import axios from 'axios';
import 'vue-cropper/dist/index.css';
import { VueCropper } from 'vue-cropper';
import { Plus } from '@element-plus/icons-vue';
import useUserStore from '@/store/modules/user';
import { useAppStore } from '@/store/modules/app';
import { UploadRawFile } from 'element-plus';
import { globalHeaders } from '@/utils/request';
const userStore = useUserStore();
const appStore = useAppStore();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const props = defineProps({
  limit: {
    type: Number,
    default: 1
  },
  fixedBox: {
    type: Boolean,
    default: true
  },
  advertiserId: {
    type: String
  },
  // 接受的文件类型
  accept: {
    type: String,
    default: 'image/*'
  },
  // 是否禁用
  disabled: Boolean,
  // 提示文字
  tip: String,
  // 对话框标题
  dialogTitle: {
    type: String,
    default: '图片裁剪'
  },
  // 裁剪后图片质量 (0.1 - 1)
  outputSize: {
    type: Number,
    default: 1
  },
  // 裁剪后图片格式 (jpeg/png/webp)
  outputType: {
    type: String,
    default: 'png'
  },
  // 是否显示裁剪信息
  showInfo: {
    type: Boolean,
    default: true
  },
  // 是否输出原图比例的截图
  full: {
    type: Boolean,
    default: false
  },
  // 是否允许移动图片
  canMove: {
    type: Boolean,
    default: true
  },
  // 是否允许移动裁剪框
  canMoveBox: {
    type: Boolean,
    default: true
  },
  // 是否固定裁剪框大小
  fixed: {
    type: Boolean,
    default: false
  },
  // 固定裁剪框比例 [宽度, 高度]
  fixedNumber: {
    type: Array,
    default: () => [1, 1]
  },
  // 是否按照原始比例渲染
  original: {
    type: Boolean,
    default: false
  },
  // 是否默认生成截图
  autoCrop: {
    type: Boolean,
    default: true
  },
  // 默认生成截图宽度
  autoCropWidth: {
    type: Number,
    default: 140
  },
  // 默认生成截图高度
  autoCropHeight: {
    type: Number,
    default: 280
  },
  // 截图框是否限制在图片内
  centerBox: {
    type: Boolean,
    default: true
  },
  // 是否高清
  high: {
    type: Boolean,
    default: true
  },
  // 图片显示模式 (contain/cover)
  mode: {
    type: String,
    default: 'contain'
  },
  // 是否显示旋转按钮
  showRotate: {
    type: Boolean,
    default: true
  },
  // 是否显示翻转按钮
  showFlip: {
    type: Boolean,
    default: true
  },
  // 是否显示重置按钮
  showReset: {
    type: Boolean,
    default: true
  },
  // 最大文件大小 (MB)
  maxSize: {
    type: Number,
    default: 5
  }
});
const baseUrl = import.meta.env.VITE_APP_BASE_API;

const emit = defineEmits(['crop-success', 'crop-error']);
const uploadImgUrl = ref(baseUrl + 'oce/upload/image'); // 上传的图片服务器地址
const headers = ref(globalHeaders());
/** 覆盖默认上传行为 */
const requestUpload = (): any => {};
const fileList = ref([]);
const oldFileList = ref([]);
interface Options {
  img: string | any; // 裁剪图片的地址
  autoCrop: boolean; // 是否默认生成截图框
  autoCropWidth: number; // 默认生成截图框宽度
  autoCropHeight: number; // 默认生成截图框高度
  fixedBox: boolean; // 固定截图框大小 不允许改变
  fileName: string;
  previews: any; // 预览数据
  outputType: string;
  visible: boolean;
}
//图片裁剪数据
const options = reactive<Options>({
  img: userStore.avatar,
  // img: '',
  autoCrop: true,
  autoCropWidth: props.autoCropWidth,
  autoCropHeight: props.autoCropHeight,
  fixedBox: true,
  outputType: 'png',
  fileName: '',
  previews: {},
  visible: false
});
const uploadRef = ref(null);
const cropperRef = ref(null);
const cropperVisible = ref(false);
const cropperImg = ref('');
const currentFile = ref<File | null>(null);
const handleExceed = () => {
  proxy?.$modal.msgError('最多上传' + props.limit + '张图片');
};
/** 实时预览 */
const realTime = (data: any) => {
  options.previews = data;
};
// 处理文件选择
const handleFileChange = async (file: UploadFile) => {
  if (!file.raw) return; // 没有文件
  const dataUrl = await readFileAsDataURL(file.raw);
  cropperImg.value = dataUrl;
  cropperVisible.value = true;
};
// 封装为 Promise 的文件读取函数
const readFileAsDataURL = (file: File): Promise<string> => {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.onload = (e) => resolve(e.target?.result as string);
    reader.onerror = reject;
    reader.readAsDataURL(file);
  });
};
// 确认裁剪
const handleCrop = () => {
  cropperRef.value.getCropBlob(async (data: any) => {
    // const croppedFile = new File([data], options.fileName, {
    //   type: `image/${options.outputType}`,
    //   lastModified: Date.now()
    // });
    // 创建临时URL用于获取图片尺寸
    console.log(data, 'data');

    const imgUrl = URL.createObjectURL(data);
    const img = new Image();

    img.onload = async () => {
      const width = img.width;
      const height = img.height;
      console.log('裁剪后图片尺寸:', width, height);

      // 创建文件对象（包含尺寸信息）
      const croppedFile = new File([data], options.fileName, {
        type: `image/${options.outputType}`,
        lastModified: Date.now()
      });

      // 上传文件（可传递宽高信息）
      await uploadCroppedImage(croppedFile, width, height);
      console.log('width', width);

      // 释放临时URL
      URL.revokeObjectURL(imgUrl);
    };

    img.src = imgUrl;
    // console.log('croppedFile', croppedFile);
    // 调用手动上传的函数
    // await uploadCroppedImage(croppedFile);
  });
};
//
const cancel = () => {
  cropperVisible.value = false;
  oldFileList.value.forEach((oldFile) => {
    const index = fileList.value.findIndex((file) => file.uid === oldFile.uid);
    if (index !== -1) {
      fileList.value.splice(index, 1);
    }
  });
};
const uploadCroppedImage = async (file: File, width, height) => {
  const formData = new FormData();
  formData.append('file', file);
  formData.append('accountId', appStore.accountId + '');
  formData.append('advertiserId', props.advertiserId);
  try {
    const response = await axios.post(uploadImgUrl.value, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });

    if (response.data.code === 200) {
      fileList.value.push({
        name: file.name,
        width: width,
        height: height,
        url: response.data.data.url, // 服务器返回的图片 URL
        status: 'success' // 标记为上传成功
      });
      // 根据oldFileList的uid在fileList.value中找到对应的文件并删除
      oldFileList.value.forEach((oldFile) => {
        const index = fileList.value.findIndex((file) => file.uid === oldFile.uid);
        if (index !== -1) {
          fileList.value.splice(index, 1);
        }
      });
      console.log(fileList.value, 'fileList.value');
      cropperVisible.value = false;
      // 触发成功事件
      emit('crop-success', fileList.value);
      proxy?.$modal.msgSuccess('上传成功');
    } else {
      emit('crop-error', new Error('上传失败'));
    }
  } catch (error) {
    emit('crop-error', error);
    proxy?.$modal.msgError('上传失败');
  }
};
/** 上传预处理 */
const beforeUpload = (file): any => {
  if (fileList.value.length >= 8) {
    proxy?.$modal.msgError('最多上传8张图片');
    return false;
  }
  if (file.raw.type.indexOf('image/') == -1) {
    proxy?.$modal.msgError('文件格式错误，请上传图片类型,如：JPG，PNG后缀的文件。');
    return false; // 阻止上传
  } else {
    oldFileList.value.push(file);
    console.log('file3', oldFileList.value);
    const reader = new FileReader();
    reader.readAsDataURL(file.raw);
    reader.onload = () => {
      options.img = reader.result;
      options.fileName = file.name;
      cropperVisible.value = true;
      return false; // 阻止默认上传行为
    };
  }
};

// 旋转图片
const rotateImage = () => {
  cropperRef.value?.rotateRight();
};

// 翻转图片
const flipImage = () => {
  cropperRef.value?.flipX();
};

// 重置裁剪器
const resetCropper = () => {
  // cropperRef.value?.refresh();
};
</script>

<style scoped lang="scss">
.cropper-upload {
  display: inline-block;

  :deep(.el-upload) {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);

    &:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon {
      font-size: 28px;
      color: #8c939d;
      width: 148px;
      height: 148px;
      text-align: center;
    }
  }

  .el-upload__tip {
    font-size: 12px;
    color: var(--el-text-color-secondary);
    margin-top: 7px;
  }

  .cropper-wrapper {
    width: 100%;
    height: 500px;
    position: relative;

    :deep(.vue-cropper) {
      background-color: #f8f8f8;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
.imgafter {
  position: absolute;
  top: 50%;
  transform: translate(-50%, -50%);
  box-shadow: 0 0 4px #ccc;
  overflow: hidden;
  left: 50%;
}
</style>
